package cellmaker

import (
	"gitee.com/ymofen/h3/pkg/adapter"
	"github.com/uber/h3-go/v4"
	"net/url"
	"strconv"
)

type IntByName interface {
	IntByName(name string, def int) int
}

type CellMaker struct {
	lvl int
}

func (this *CellMaker) GetCell(b0, l0, h0 float64) (id interface{}, b, l, h float64) {
	lat, lng := b0, l0
	index, err := h3.LatLngToCell(h3.LatLng{Lat: lat, Lng: lng}, this.lvl)
	if err != nil {
		panic(err)
	}
	ll, _ := index.LatLng()
	return index.String(), ll.Lat, ll.Lng, h0
}

// lvl=7
func CreateCellMaker(args ...interface{}) (rval interface{}, err error) {
	lvl := 0
	if intf, ok := args[0].(IntByName); ok {
		lvl = intf.IntByName("lvl", 7)
	} else if s, ok := args[0].(string); ok {
		valMap, err := url.ParseQuery(s)
		if err != nil {
			return nil, err
		}
		sv := valMap.Get("lvl")
		lvl, err = strconv.Atoi(sv)
		if err != nil {
			return nil, err
		}
	}

	rval = &CellMaker{lvl: lvl}
	return
}

func Initial() {
	err := adapter.RegisterCreateFunc("cell.h3", CreateCellMaker)
	if err != nil {
		adapter.LogPrintf("register CreateFunc err: %v", err)
	}
}
